package com.sk.coin.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.sk.coin.model.WebLog;
import com.sk.coin.sys.entity.SysUserLog;
import com.sk.coin.sys.service.ISysUserLogService;
import com.sk.coin.utils.ContextUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: SongKun
 * @date: 2022/3/6
 * @Description: 系统日志记录
 */

@Component
@Aspect
@Order(2)
@Slf4j
public class WebLogAdminAspect {

    @Autowired
    private ISysUserLogService sysUserLogService;

    /**
     * 定义切入点
     */
    @Pointcut("execution(* com.sk.coin.controller.*.*(..))")
    public void webLog(){}

    @Around("webLog()")
    public Object recodeWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = null;
        WebLog webLog = new WebLog();
        long start = System.currentTimeMillis();
        // 执行切面内的方法
        result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end = System.currentTimeMillis();
        // 接口的花费时间
        webLog.setSpendTime((int)(start-end)/1000);
        HttpServletRequest request = ContextUtil.getRequest();
        String url = request.getRequestURL().toString();
        webLog.setUrl(url);
        webLog.setUri(request.getRequestURI());
        // http://ip:port
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        webLog.setUsername(ContextUtil.getStrUserId() == null ? "anonymous" : ContextUtil.getStrUserId());
        webLog.setIp(request.getRemoteAddr());
        // 获取类的名称
        String targetClassName = proceedingJoinPoint.getTarget().getClass().getName();
        // 获取方法
        MethodSignature signature = (MethodSignature)proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        // 获取方法上Swagger的ApiOperation注解
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(annotation == null ? "no desc" : annotation.value());
        // com.sk.coin.controller.UserController.login()
        webLog.setMethod(targetClassName + "." + method.getName());
        // {"key_参数的名称":"value_参数的值"}
        webLog.setParameter(getMethodParameter(method,proceedingJoinPoint.getArgs()));
        webLog.setResult(result);
        SysUserLog sysUserLog = new SysUserLog();
        sysUserLog.setDescription(webLog.getDescription());
        sysUserLog.setGroup(webLog.getDescription());
        sysUserLog.setUserId(ContextUtil.getUserId());
        sysUserLog.setMethod(webLog.getMethod());
        sysUserLog.setIp(sysUserLog.getIp());
        sysUserLogService.save(sysUserLog) ;
        return result ;
    }

    private Object getMethodParameter(Method method, Object[] args) {
        Map<String,Object> methodParametersWithValues = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer =
                new LocalVariableTableParameterNameDiscoverer();
        // 方法的形参名称
        String[] parameterNames = localVariableTableParameterNameDiscoverer
                .getParameterNames(method);
        if (parameterNames != null) {
            for (int i = 0; i <parameterNames.length ; i++) {
                if(parameterNames[i].equals("password") ||
                        parameterNames[i].equals("file")) {
                    methodParametersWithValues.put(parameterNames[i],"受限的支持类型");
                } else {
                    methodParametersWithValues.put(parameterNames[i],args[i]);
                }
            }
        }
        return methodParametersWithValues;
    }

}
